/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseresourcesService;
import me.zhengjie.modules.system.domain.vo.CourseresourcesQueryCriteria;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-12-12
**/
@Service
@RequiredArgsConstructor
public class CourseresourcesServiceImpl extends ServiceImpl<CourseresourcesMapper, Courseresources> implements CourseresourcesService {

    private final CourseresourcesMapper courseresourcesMapper;

    private final UserMapper userMapper;

    private final CourseresourcescatalogMapper courseresourcescatalogMapper;

    private final CourseresourcesmsgMapper courseResourcesMsgMapper;

    private final TeacherMapper teacherMapper;

    private final DepartmentteacherMapper departmentteacherMapper;


    @Override
    public PageResult<Courseresources> queryAll(CourseresourcesQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(Math.toIntExact(currentUser.getDeptId()));
        criteria.setUserId(Math.toIntExact(currentUser.getId()));
        IPage<Courseresources> pageMsg = courseresourcesMapper.findAll(criteria, page);
        List<Courseresources> courseresourcesList = pageMsg.getRecords();

        //获取资源id
        List<Integer> courseresourcesIds = new ArrayList<>();

        //获取用户id
        List<Integer> createUserIds = new ArrayList<>();
        for(Courseresources courseresources:courseresourcesList){
            courseresourcesIds.add(courseresources.getId());
            createUserIds.add(courseresources.getCreateUserId());
        }


        //获取所有目录
        List<Courseresourcescatalog> courseresourcescatalogList = new ArrayList<>();
        List<Courseresourcescatalog> courseresourcescatalogList2 = new ArrayList<>();
        if(courseresourcesIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseResourcesId",courseresourcesIds);
            courseresourcescatalogList = courseresourcescatalogMapper.selectList(queryWrapper);

            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("courseResourcesId",courseresourcesIds);
//            queryWrapper2.in("state",2);
            courseresourcescatalogList2 = courseresourcescatalogMapper.selectList(queryWrapper2);




        }
        //获取创建资源用户用户
        List<User> userList = new ArrayList<>();
        if(createUserIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id",createUserIds);
            userList = userMapper.selectList(queryWrapper);
        }


        //获取通过目录


        //获取所有资源目录id
        List<Integer>  courseResourcesCatalogIds = new ArrayList<>();
        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
            courseResourcesCatalogIds.add(courseresourcescatalog.getId());
        }

        List<Courseresourcesmsg> courseresourcesmsgList = new ArrayList<>();
        if(courseResourcesCatalogIds.size()!=0){
            //获取所有资源
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("courseResourcesCatalogId",courseResourcesCatalogIds);
            courseresourcesmsgList = courseResourcesMsgMapper.selectList(queryWrapper1);
        }



        //绑定计算信息
        for(Courseresources courseresources:courseresourcesList){
            //所有目录数量
            for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
                if(courseresourcescatalog.getCourseresourcesId() == courseresources.getId()){


                    if(courseresources.getAllNum()==null){
                        courseresources.setAllNum(1);
                    } else {
                        courseresources.setAllNum(courseresources.getAllNum()+1);
                    }

                }
            }
            //通过目录数量
            for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList2){
                if(courseresourcescatalog.getCourseresourcesId() == courseresources.getId()){


                    //通过
                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 2){
                        if(courseresources.getPassNum() == null){
                            courseresources.setPassNum(1);
                        } else {
                            courseresources.setPassNum(courseresources.getPassNum()+1);
                        }
                    }

                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 3){
                        //驳回
                        if(courseresources.getRejectNum() == null){
                            courseresources.setRejectNum(1);
                        } else {
                            courseresources.setRejectNum(courseresources.getRejectNum()+1);
                        }
                    }


                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 1){
                        //待审核
                        if(courseresources.getAuditNum() == null){
                            courseresources.setAuditNum(1);
                        } else {
                            courseresources.setAuditNum(courseresources.getAuditNum()+1);
                        }
                    }


                    //资源数量
//                    for(Courseresourcesmsg courseresourcesmsg:courseresourcesmsgList){
//                        if(courseresourcesmsg.getCourseresourcescatalogId() == courseresourcescatalog.getId()){
//                            if(courseresourcesmsg.getType() == 0){
//                                courseresources.setImgNum(courseresources.getImgNum()+1);
//                            } else if(courseresourcesmsg.getType() == 2){
//                                courseresources.setVideoNum(courseresources.getVideoNum()+1);
//                            }else if(courseresourcesmsg.getType() == 6){
//                                courseresources.setFileNum(courseresources.getFileNum()+1);
//                            }
//                        }
//                    }

                    for(Courseresourcesmsg courseresourcesmsg:courseresourcesmsgList){
                        if(courseresourcesmsg.getCourseresourcescatalogId() == courseresourcescatalog.getId()){

                            if(courseresourcesmsg.getType() == 0){
                                if(courseresources.getImgNum() == null){
                                    courseresources.setImgNum(1);
                                } else {
                                    courseresources.setImgNum(courseresources.getImgNum()+1);
                                }

                            } else if(courseresourcesmsg.getType() == 2){
                                if(courseresources.getVideoNum() == null){
                                    courseresources.setVideoNum(1);
                                } else {
                                    courseresources.setVideoNum(courseresources.getVideoNum()+1);
                                }

                            }else if(courseresourcesmsg.getType() == 6){

                                if(courseresources.getFileNum() == null){
                                    courseresources.setFileNum(1);
                                } else {
                                    courseresources.setFileNum(courseresources.getFileNum()+1);
                                }

                            }
                        }
                    }

                }
            }




            for(User user:userList){
                if(courseresources.getCreateUserId()!=null && courseresources.getCreateUserId() == Math.toIntExact(user.getId())){
                    courseresources.setCreateUserName(user.getNickName());
                }
            }
        }
        return PageUtil.toPage(pageMsg);
    }


    public PageResult<Courseresources> queryAuditCourseresources(CourseresourcesQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(Math.toIntExact(currentUser.getDeptId()));

        //获取教师
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper1);

        QueryWrapper queryWrapper4 = new QueryWrapper();
        queryWrapper4.in("teacherId",teacher.getId());
        Departmentteacher departmentteacher = departmentteacherMapper.selectOne(queryWrapper4);

        //获取部门教师
        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("departmentId",departmentteacher.getDepartmentId());
        List<Departmentteacher> departmentteacherList = departmentteacherMapper.selectList(queryWrapper3);

        List<Integer> teacherIds = new ArrayList<>();
        for(Departmentteacher departmentteacher1:departmentteacherList){
            teacherIds.add(departmentteacher1.getTeacherId());
        }

        List<Integer> stateArr = new ArrayList<>();
        stateArr.add(1);
        stateArr.add(2);
        stateArr.add(3);
        criteria.setStateArr(stateArr);
        if(teacherIds.size()!=0){
            criteria.setTeacherIds(teacherIds);
        }
        IPage<Courseresources> pageMsg = courseresourcesMapper.findAuditAll(criteria, page);
        List<Courseresources> courseresourcesList = pageMsg.getRecords();

        List<Courseresources> courseresourcesList2 = new ArrayList<>();
        //获取资源id
        List<Integer> courseresourcesIds = new ArrayList<>();

        //获取用户id
        List<Integer> createUserIds = new ArrayList<>();
        for(Courseresources courseresources:courseresourcesList){
            courseresourcesIds.add(courseresources.getId());
            createUserIds.add(courseresources.getCreateUserId());
        }


        //获取所有目录
        List<Courseresourcescatalog> courseresourcescatalogList = new ArrayList<>();
        List<Courseresourcescatalog> courseresourcescatalogList2 = new ArrayList<>();
        if(courseresourcesIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseResourcesId",courseresourcesIds);
            courseresourcescatalogList = courseresourcescatalogMapper.selectList(queryWrapper);

            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("courseResourcesId",courseresourcesIds);
//            queryWrapper2.in("state",2);
            courseresourcescatalogList2 = courseresourcescatalogMapper.selectList(queryWrapper2);

        }
        //获取创建资源用户用户
        List<User> userList = new ArrayList<>();
        if(createUserIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id",createUserIds);
            userList = userMapper.selectList(queryWrapper);
        }


        //获取通过目录


        //获取所有资源目录id
        List<Integer>  courseResourcesCatalogIds = new ArrayList<>();
        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
            courseResourcesCatalogIds.add(courseresourcescatalog.getId());
        }

        List<Courseresourcesmsg> courseresourcesmsgList = new ArrayList<>();
        if(courseResourcesCatalogIds.size()!=0){
            //获取所有资源
            QueryWrapper queryWrapper5 = new QueryWrapper<>();
            queryWrapper5.in("courseResourcesCatalogId",courseResourcesCatalogIds);


            courseresourcesmsgList = courseResourcesMsgMapper.selectList(queryWrapper5);
        }
        //绑定计算信息
        for(Courseresources courseresources:courseresourcesList){
            //所有目录数量
            for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
                if(courseresourcescatalog.getCourseresourcesId() == courseresources.getId()){
                    if(courseresources.getAllNum()==null){
                        courseresources.setAllNum(1);
                    } else {
                        courseresources.setAllNum(courseresources.getAllNum()+1);
                    }

                }
            }
            //通过目录数量
            for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList2){
                if(courseresourcescatalog.getCourseresourcesId() == courseresources.getId()){

                    //通过
                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 2){
                        if(courseresources.getPassNum() == null){
                            courseresources.setPassNum(1);
                        } else {
                            courseresources.setPassNum(courseresources.getPassNum()+1);
                        }
                    }

                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 3){
                        //驳回
                        if(courseresources.getRejectNum() == null){
                            courseresources.setRejectNum(1);
                        } else {
                            courseresources.setRejectNum(courseresources.getRejectNum()+1);
                        }
                    }


                    if(courseresourcescatalog.getState()!=null && courseresourcescatalog.getState() == 1){

                        //待审核
                        if(courseresources.getAuditNum() == null){
                            courseresources.setAuditNum(1);
                        } else {
                            courseresources.setAuditNum(courseresources.getAuditNum()+1);
                        }
                    }

                    //资源数量
                    for(Courseresourcesmsg courseresourcesmsg:courseresourcesmsgList){

                        if(courseresourcesmsg.getCourseresourcescatalogId() == courseresourcescatalog.getId()){
                            if(courseresourcesmsg.getType() == 0){
                                if(courseresources.getImgNum() == null){
                                    courseresources.setImgNum(1);
                                } else {
                                    courseresources.setImgNum(courseresources.getImgNum()+1);
                                }

                            } else if(courseresourcesmsg.getType() == 2){
                                if(courseresources.getVideoNum() == null){
                                    courseresources.setVideoNum(1);
                                } else {
                                    courseresources.setVideoNum(courseresources.getVideoNum()+1);
                                }

                            }else if(courseresourcesmsg.getType() == 6){

                                if(courseresources.getFileNum() == null){
                                    courseresources.setFileNum(1);
                                } else {
                                    courseresources.setFileNum(courseresources.getFileNum()+1);
                                }

                            }
                        }
                    }
                }


            }

            for(User user:userList){
                if(courseresources.getCreateUserId()!=null && courseresources.getCreateUserId() == Math.toIntExact(user.getId())){
                    courseresources.setCreateUserName(user.getNickName());
                }
            }

            if(courseresources.getAuditNum()!=null && courseresources.getAuditNum() != 0){

                courseresourcesList2.add(courseresources);
            }
        }

        pageMsg.setRecords(courseresourcesList2);
        return PageUtil.toPage(pageMsg);
    }

    @Override
    public List<Courseresources> queryAll(CourseresourcesQueryCriteria criteria){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(Math.toIntExact(currentUser.getDeptId()));
        criteria.setUserId(Math.toIntExact(currentUser.getId()));
        return courseresourcesMapper.findAll(criteria);
    }


    @Override
    public List<Courseresources> queryAuditCourseresources(CourseresourcesQueryCriteria criteria){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(Math.toIntExact(currentUser.getDeptId()));

        return courseresourcesMapper.findAuditAll(criteria);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Courseresources resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        resources.setSchoolId(Math.toIntExact(currentUser.getDeptId()));

        if(teacher!=null){
            resources.setTeacherId(Math.toIntExact(teacher.getId()));
        }
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
        // 将 LocalDateTime 按照定义的格式进行格式化
        String formattedDateTime = now.format(formatter);

        resources.setCreateTime(formattedDateTime);
        resources.setCreateUserId(Math.toIntExact(currentUser.getId()));


        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Courseresources resources) {
        Courseresources courseresources = getById(resources.getId());
        courseresources.copy(resources);
        saveOrUpdate(courseresources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("courseResourcesId",ids);
        courseresourcescatalogMapper.delete(queryWrapper);

    }

    @Override
    public void download(List<Courseresources> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Courseresources courseresources : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" name",  courseresources.getName());
            map.put(" teacherId",  courseresources.getTeacherId());
            map.put(" schoolId",  courseresources.getSchoolId());
            map.put(" lastupdatetime",  courseresources.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}